package com.hm.email.service;

import java.io.File;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.hm.common.common.CommonUtil;
import com.hm.common.exception.ServiceException;
import com.hm.email.mongo.domain.Email;
import com.hm.email.mongo.domain.def.EmailTypeDef;
import com.hm.email.share.repository.EmailRepository;
import com.hm.email.share.service.SendEmailService;
import com.hm.email.util.EmailFactory;
import com.hm.email.util.EmailModel;
import com.hm.email.vo.EmailVo;

/**
 * @author shishun.wang
 * @date 下午4:50:06 2016年6月16日
 * @version 1.0
 * @describe 
 */
@Service
public class SendEmailServiceImpl implements SendEmailService {

	@Autowired
	private EmailRepository emailRepository;
	
	@Autowired
	private EmailFactory factory;

	@Override
	public String send(EmailVo emailModel, EmailTypeDef emailType, String operationUser) {
		try {
			if(CommonUtil.isAnyEmpty(emailModel.getRecipient(),emailModel.getTheme())){
				throw ServiceException.warn("邮件主题和邮件接收人不能为null");
			}
			
			Email email = new Email();
			{
				email.setRecipient(emailModel.getRecipient());
				email.setTheme(emailModel.getTheme());
				email.setContent(emailModel.getContent());
				email.setCopyTo(emailModel.getCopyTo());
			}
			if(CollectionUtils.isEmpty(emailModel.getRecipient())){
				factory.send(emailModel);
			}else{
				factory.send(emailModel.getRecipient(), email.getTheme(), email.getContent());
			}
			
			return emailRepository.save(email).getId();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String send(EmailVo emailModel, EmailTypeDef emailType, String operationUser, File[] files) {
		try {
			if(CommonUtil.isAnyEmpty(emailModel.getRecipient(),emailModel.getTheme())){
				throw ServiceException.warn("邮件主题和邮件接收人不能为null");
			}
			
			Email email = new Email();
			{
				email.setRecipient(emailModel.getRecipient());
				email.setTheme(emailModel.getTheme());
				email.setContent(emailModel.getContent());
				email.setCopyTo(emailModel.getCopyTo());
			}
			
			EmailModel[] emailModels = new EmailModel[files.length];
			for(int i = 0 ; i < files.length ; i++){
				EmailModel model = new EmailModel();
				model.setFile(files[i]);
				model.setName(files[i].getName());
			}
			
			if(CollectionUtils.isEmpty(emailModel.getRecipient())){
				factory.send(emailModel, emailModels);
			}else{
				factory.send(emailModel.getRecipient(), email.getTheme(), email.getContent(),emailModels);
			}
			
			return emailRepository.save(email).getId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
